package com.burgeon.backend.WeChat;

import com.burgeon.backend.EnterpriseWeChat.service.ex.UpDataException;
import com.burgeon.backend.SHOP.service.SystemService;
import com.burgeon.backend.SHOPBACKEND.mappers.AndroidMapper;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import com.google.gson.Gson;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.codec.binary.Base64;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 获取小程序二维码
 */
@Component
public class Wxacode {
    private final static Log logger = LogFactory.getLog(Wxacode.class);

    // 永久二维码(字符串)
    private final static String QR_LIMIT_STR_SCENE = "QR_LIMIT_STR_SCENE";
    // 创建二维码
    private String create_ticket_path = "https://api.weixin.qq.com/cgi-bin/qrcode/create";
    // 通过ticket换取二维码
    private String showqrcode_path = "https://mp.weixin.qq.com/cgi-bin/showqrcode";

    @Autowired
    private AndroidMapper androidMapper;
    @Autowired
    private SystemService systemService;

    /**
     * 推荐客户有礼
     * @param uid
     * @param accessToken
     * @return
     * @throws ErrorDataException
     */
    public String recommendCode(String uid, String accessToken,String token) throws ErrorDataException {
        System.err.println("*****************************");
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String sceneStr="rd="+uid+"&"+"linkpage=i"+"&empName="+"";
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            Map<String,Object> param = new HashMap<>();
            //pages/product/productDetail/productDetail.html?id=351
            param.put("scene", sceneStr);
//            param.put("page", "pages/product/productDetail/productDetail");
            param.put("page", "pages/userStart/userStart");//小程序跳转页面
            param.put("width", 430);

            param.put("auto_color", false);
            Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            System.err.println(requestEntity);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + Arrays.toString(entity.getBody()));
            byte[] result = entity.getBody();

            inputStream = new ByteArrayInputStream(result);

            // 上传后的路径code
            String filePath = "//root//code//img//" + "recommendCode//" + token +"//" + uid + ".png";
            File file = new File(filePath);
            if (!file.exists()){
                file.getParentFile().mkdirs();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();//http://lfwd.cloudsmicro.com

            return "http://lfwd.cloudsmicro.com:8080/img/" + "recommendCode/" + token +"/" + uid + ".png";
        } catch (Exception e) {
            logger.error("调用小程序生成微信永久小程序码URL接口异常",e);
            throw new ErrorDataException("调用小程序生成微信永久小程序码URL接口异常");
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String createEmpRQcode(String id, String accessToken,String account) throws ErrorDataException {
        System.err.println("id="+id);
        System.err.println("*****************************");
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String sceneStr="id="+id+"&"+"token="+account;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            Map<String,Object> param = new HashMap<>();
            //pages/product/productDetail/productDetail.html?id=351
            param.put("scene", sceneStr);
            //param.put("page", "pages/product/productDetail/productDetail");
            param.put("page", "appRegist/pages/appRegistStart/appRegistStart");
            param.put("width", 430);

            param.put("auto_color", false);
            Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            //logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + Arrays.toString(entity.getBody()));
            byte[] result = entity.getBody();

            inputStream = new ByteArrayInputStream(result);

            // 上传后的路径code
            String filePath = "//root//code//img//" + "empRQcode//" + account +"//" + id + ".png";   File file = new File(filePath);
            if (!file.exists()){
                file.getParentFile().mkdirs();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();//http://lfwd.cloudsmicro.com

            return "http://lfwdcdn.cloudsmicro.com/img/" + "empRQcode/" + account +"/" + id + ".png";
        } catch (Exception e) {
            logger.error("调用小程序生成微信永久小程序码URL接口异常",e);
            throw new ErrorDataException("调用小程序生成微信永久小程序码URL接口异常");
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //绑定客服推送通知的二维码
    public String createKfcode(String accessToken,String account) throws ErrorDataException {
//        System.err.println("id="+id);
//        System.err.println("*****************************");
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String sceneStr="token="+account;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            Map<String,Object> param = new HashMap<>();
            //pages/product/productDetail/productDetail.html?id=351
            param.put("scene", sceneStr);
            //param.put("page", "pages/product/productDetail/productDetail");
            param.put("page", "appRegist/pages/daogouTrains/daogouTrains");
            param.put("width", 430);

            param.put("auto_color", false);
            Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            //logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + Arrays.toString(entity.getBody()));
            byte[] result = entity.getBody();
            logger.info(Base64.encodeBase64String(result));
            inputStream = new ByteArrayInputStream(result);

            // 上传后的路径code
            String filePath = "//root//code//img//" + "kfCode//" + account +"//" + account + ".png";
            File file = new File(filePath);
            if (!file.exists()){
                file.getParentFile().mkdirs();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();//http://lfwd.cloudsmicro.com

            return "http://lfwd.cloudsmicro.com:8080/img/" + "kfCode/" + account +"/" + account + ".png";
        } catch (Exception e) {
            logger.error("调用小程序生成微信永久小程序码URL接口异常",e);
            throw new ErrorDataException("调用小程序生成微信永久小程序码URL接口异常");
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 商品小程序码
     * @param id
     * @param accessToken
     * @param account
     * @param daoId
     * @return
     */
    public String getminiqrQr(String id, String accessToken,String account,String daoId) {

        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String sceneStr="id="+id+"&daoId="+daoId+"&token="+account;
        //String sceneStr="id="+id+"&"+"token="+account+"&"+"daoId="+daoId;
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            Map<String,Object> param = new HashMap<>();
            //pages/product/productDetail/productDetail.html?id=351
            param.put("scene", sceneStr);
            //param.put("page", "pages/product/productDetail/productDetail");
           // param.put("page", "pages/product/productDetail/productDetail");
            param.put("page", "appRegist/pages/appProductDetail/appProductDetail");
            param.put("width", 430);

            param.put("auto_color", false);
            Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
//            logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + Arrays.toString(entity.getBody()));
            byte[] result = entity.getBody();
            String isError=new String(result);
            if (isError.contains("errcode")){
                logger.info("请求失败的情况:" + isError);
                JSONObject jsonObject = new JSONObject(isError);
                if(jsonObject.getString("errcode").equals("40001")){
                    accessToken = systemService.AgainGetAccessToken(account);
                    url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
                    entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
                    result = entity.getBody();
                    logger.info("重新请求:" + new String(result));
                }else if(jsonObject.getString("errcode").equals("45009")){
                    throw new UpDataException("目前有大量用户访问，请稍后访问");
//                    logger.info("大量:" + new String(result));
                }

            }
                inputStream = new ByteArrayInputStream(result);

                // 上传后的路径code
                String filePath = "//root//code//img//" + account + "-WaMaterial//" + id +"-"+daoId + ".png";
                //String furl = "http://lfwd.cloudsmicro.com/img/" + account + "-Wamaterial/" + id + "/.png";
                File file = new File(filePath);
                if (!file.exists()){
                    file.getParentFile().mkdirs();
                }
                outputStream = new FileOutputStream(file);
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                    outputStream.write(buf, 0, len);
                }
                outputStream.flush();
                String furl = "http://lfwd.cloudsmicro.com:8080/img/" + account + "-WaMaterial/" + id+"-"+daoId + ".png";
                androidMapper.insertLinkImg(id,furl,daoId,account);
                return furl;

        } catch (Exception e) {
            logger.error("调用小程序生成微信永久小程序码URL接口异常",e);
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * @author: 伯俊软件
     * @description: 获取ticket值
     * @date: 2021/7/8 16:09
     * @param accessToken
     * @param token
     * @return
     */
    public String createForeverStrTicket(String accessToken,String token){

        TreeMap<String, String> params = new TreeMap<>();
        params.put("access_token", accessToken);

        HashMap<String, String> intMap = new HashMap<>();
        String sceneStr="token="+token;
        intMap.put("scene_str",sceneStr);

        HashMap<String, Map<String, String>> mapMap = new HashMap<>();
        mapMap.put("scene",intMap);

        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("action_info", mapMap);
        paramsMap.put("action_name", QR_LIMIT_STR_SCENE);

        String data = new Gson().toJson(paramsMap);

        System.err.println("===="+data);

        data =  HttpRequestUtil.HttpsDefaultExecute(HttpRequestUtil.POST_METHOD,create_ticket_path,params,data);

        WeiXinQRCode wxQRCode = null;
        try {
            wxQRCode = new Gson().fromJson(data, WeiXinQRCode.class);
        } catch (Exception e) {
            wxQRCode = null;
        }
        return wxQRCode==null?null:wxQRCode.getTicket();
    }

    /**
     * @author: 伯俊软件
     * @description: 根据ticket换取公众号二维码
     * @date: 2021/7/8 16:08
     * @param ticket
     * @return
     */
    public String showQrcode(String ticket){
        TreeMap<String, String> params = new TreeMap<>();
        params.put("ticket", HttpRequestUtil.urlEncode(ticket, HttpRequestUtil.DEFAULT_CHARSET));
        try {
            showqrcode_path = HttpRequestUtil.setParmas(params,showqrcode_path,"");
        }catch (Exception e){
            e.printStackTrace();
        }
        return showqrcode_path;
    }

    /**
     * @author: 伯俊软件
     * @description: 获取公众号头像、名称
     * @date: 2021/7/8 17:19
     * @param accessToken
     * @return
     */
    public WeiXinQRCode showInfo(String accessToken){

        RestTemplate rest = new RestTemplate();

        String url = "https://api.weixin.qq.com/wxa/getshowwxaitem?access_token="+accessToken;

        WeiXinQRCode weiXinQRCode = null;
        try {
            weiXinQRCode = rest.getForObject(url, WeiXinQRCode.class);

        }catch (Exception e){
            e.printStackTrace();
        }
        return weiXinQRCode;

    }
}


